﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Pibby.Controls;
using Pibby.Core;
using Pibby.Core.Logging;
using Pibby.Core.Models;
using Pibby.Core.Persistence;
using Pibby.Core.PortableMedia;
using Pibby.Core.Presenters;
using Pibby.Core.Views;

using Pibby.Core.IO;
using Pibby.Core.ViewModels;
using Pibby.Core.Opml;
using Pibby.Core.Playlist;
using invrt;

namespace Pibby.UI
{
    public partial class MainForm : Form, IShowProgress, IPodcatcherView
	{
		#region Constants

		enum TabbedPageView
		{
			NewEpisodes = 0,
			DownloadedEpisodes,
			MediaPlayer,
			MediaPlayerContent,
			Subscriptions,
			BackCatalog
		}

		//private const int HomePageIndex = 0;
		//private const int PortableDevicePageIndex = 1;
		//private const int InboxPageIndex = 2;
		//private const int BackCatalogPageIndex = 3;
		//private const int PortableDeviceContentPageIndex = 4;
		//private const int SubscriptionPageIndex = 5;

		const string MainFormAppID = "Pibby.UI.MainFormAppID";

		#endregion Constants

		#region IPodcatcherView events

		public event EventHandler Initialising;
		public event EventHandler InitialiseComplete;

		public event EventHandler<NewPodcastEventArgs> AddPodcast;

		public event EventHandler SubscriptionsSelected;

		public event EventHandler<PodcastEventArgs> PodcastSelected;

		public event EventHandler<PortableMediaSettingsEventArgs> PortableMediaSettingsChanged;
		public event EventHandler<RemovableDriveEventArgs> RemovableDeviceArrived;
		public event EventHandler<RemovableDriveEventArgs> RemovableDeviceRemoved;

		public event EventHandler RefreshPortableDevice;

		public event EventHandler<TransferCommandEventArgs> TransferContent;

		public event EventHandler EjectDevice = null;

		//public event EventHandler<SubViewEventArgs> SubViewChanged;

		public event EventHandler RefreshNavigationList;

		public event EventHandler CheckForEpisodes;

		public event EventHandler<EpisodeEventArgs> IgnoreEpisode = null;

		public event EventHandler NewEpisodesSelected;

		public event EventHandler DownloadsSelected;

		//public event EventHandler<EpisodeEventArgs> SelectEpisode = null;
		//public event EventHandler<EpisodeEventArgs> SelectEpisodeForDownload = null;
		//public event EventHandler SelectAllEpisodesForDownload = null;
		//public event EventHandler ClearAllEpisodesForDownload = null;

		public event EventHandler<EpisodeDownloadEventArgs> DownloadEpisodes;

		public event EventHandler<SearchEventArgs> SearchPodcasts;
		public event EventHandler<PodcastSearchEventArgs> SearchPodcast;
		public event EventHandler<SearchEventArgs> SearchEpisodes;

		public event EventHandler<FilePersistenceEventArgs> ImportPodcasts;
		public event EventHandler<MultiFilePersistenceEventArgs> CopyFiles;
		public event EventHandler<FilePersistenceEventArgs> CopyPlaylist;

		public event EventHandler ClosingView;

		#endregion
		
		#region Properties

		private PodcatcherPresenter Presenter { get; set; }
		private RemovableDriveDetector DriveDetector { get; set; }

		/// <summary>
		///  need to get this from a config file.
		/// </summary>
		public int TooltipTimeout
		{
			get;
			set;
		}

		public bool ShowTooltips
		{
			get;
			set;
		}

		public int CurrentView
		{
			get
			{
				return this.multiPageTabControl.SelectedIndex;
			}
		}

		public int SplitterDistance
		{
			get
			{
				return this.splitContainer.SplitterDistance;
			}
		}

		//public SubView SubView
		//{
		//    get;
		//    private set;
		//}

        private bool Refreshing { get; set; }
		private int RefreshingItemCount { get; set; }
        private bool Downloading { get; set; }
		private int DownloadingItemCount { get; set; }
        private bool Transferring { get; set; }
		private int TransferringItemCount { get; set; }

		#endregion Properties

		#region Constructors

		public MainForm(IPodcatcherModel model)
        {
            InitializeComponent();

			this.SetStyle(ControlStyles.AllPaintingInWmPaint
							| ControlStyles.UserPaint
							| ControlStyles.DoubleBuffer, true);

			this.Presenter = new PodcatcherPresenter(this, model);
			this.DriveDetector = new RemovableDriveDetector();

			ConfigureAsFileDropTarget();
		}

		#endregion

		#region UI Setup

		private void ConfigureUI()
		{
			this.Text = Application.ProductName;

            this.synchPlayerButton.Enabled = false;

			this.KeyPreview = true;

			this.notifyIcon1.Icon = this.Icon;
			this.notifyIcon1.Text = string.Format("{0} - right click for options", this.Text);
			this.notifyIcon1.Visible = true;

			this.notifyIcon1.ContextMenu = new ContextMenu();
			this.notifyIcon1.ContextMenu.MenuItems.Add(new MenuItem("Open", new EventHandler(notifyContextMenuItemOpen_Click)));
			this.notifyIcon1.ContextMenu.MenuItems.Add(new MenuItem("Exit", new EventHandler(notifyContextMenuItemExit_Click)));

			this.currentSubscriptionsListView.Configure();

			this.navigationListView.Configure(this.treeViewImages);

			this.navigationListView.DeviceContentSelected += new EventHandler(navigationListView_DeviceContentSelected);
			this.navigationListView.DeviceSelected += new EventHandler(navigationListView_DeviceSelected);
			this.navigationListView.SubscriptionsSelected += new EventHandler(navigationListView_SubscriptionsSelected);
			this.navigationListView.PodcastSelected += new EventHandler<PodcastEventArgs>(navigationListView_PodcastSelected);
			this.navigationListView.NewEpisodesSelected += new EventHandler(navigationListView_NewEpisodesSelected);
			this.navigationListView.DownloadsSelected += new EventHandler(navigationListView_DownloadsSelected);

			this.podcastSubscriptionListView.SmallImageList = this.podcastImageList;
			this.podcastSpecificEpisodesListView.SmallImageList = this.episodeImageList;
			this.newEpisodesListView.SmallImageList = this.episodeImageList;
			this.downloadedEpisodesListView.SmallImageList = this.episodeImageList;

            this.newEpisodesListView.MouseUp += new MouseEventHandler(agedEpisodeListView1_MouseUp);
			this.newEpisodesListView.KeyDown += new KeyEventHandler(sortableListView_KeyDown);

            this.podcastSpecificEpisodesListView.KeyDown += new KeyEventHandler(sortableListView_KeyDown);
			// reset progress indicator
			this.Reset();
		}

		void navigationListView_DownloadsSelected(object sender, EventArgs e)
		{
			this.multiPageTabControl.SelectedIndex = (int)TabbedPageView.DownloadedEpisodes;
			this.DownloadsSelected.Fire(this);
		}

		void navigationListView_NewEpisodesSelected(object sender, EventArgs e)
		{
			this.multiPageTabControl.SelectedIndex = (int)TabbedPageView.NewEpisodes;
			this.NewEpisodesSelected.Fire(this);
		}

		void navigationListView_PodcastSelected(object sender, PodcastEventArgs e)
		{
			this.multiPageTabControl.SelectedIndex = (int)TabbedPageView.BackCatalog;
			this.PodcastSelected.Fire(this, new PodcastEventArgs(e.DbKey));
		}

		void navigationListView_SubscriptionsSelected(object sender, EventArgs e)
		{
			this.multiPageTabControl.SelectedIndex = (int)TabbedPageView.Subscriptions;
			this.SubscriptionsSelected.Fire(this);
		}

		void navigationListView_DeviceSelected(object sender, EventArgs e)
		{
			this.multiPageTabControl.SelectedIndex = (int)TabbedPageView.MediaPlayer;

			// refresh media...
		}

		void navigationListView_DeviceContentSelected(object sender, EventArgs e)
		{
			this.multiPageTabControl.SelectedIndex = (int)TabbedPageView.MediaPlayerContent;

			// refresh...
		}

        void agedEpisodeListView1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right && newEpisodesListView.SelectedItems.Count > 0)
            {
                newEpisodesListView.ContextMenuStrip = this.contextMenuStrip2;
                this.contextMenuStrip2.Show(e.X, e.Y);
            }
        }

        private void IgnoreMenu_Clicked(object sender, EventArgs e)
        {

        }

		#endregion

		#region Media Device Detection

		private const int WM_DEVICECHANGE = 0x0219;

		protected override void WndProc(ref Message m)
		{
			if (m.Msg == WM_DEVICECHANGE)
				this.DriveDetector.CheckDeviceChange(ref m);

			base.WndProc(ref m);
		}

		void DriveDetector_RemovableDriveArrived(object sender, RemovableDriveEventArgs e)
		{
			this.RemovableDeviceArrived.Fire(this, e);
		}

		void DriveDetector_RemovableDriveRemoved(object sender, RemovableDriveEventArgs e)
		{
			this.RemovableDeviceRemoved.Fire(this, e);
		}

		#endregion Media Device Detection

		#region Size and Position Persistence

        private void LoadLastSizeAndPosition(IUserSettings settings)
		{
			try
			{
				if (settings.MainWindow.Height > 0 && settings.MainWindow.Width > 0)
					this.Size = new Size(settings.MainWindow.Width, settings.MainWindow.Height);
			}
			catch (Exception ex)
			{
				Log.Error("Problem loading main window size : " + ex.Message);
			}

			try
			{
				if (settings.MainWindow.Left > 0 && settings.MainWindow.Top > 0)
					this.Location = new Point(settings.MainWindow.Left, settings.MainWindow.Top);
			}
			catch (Exception ex)
			{
				Log.Error("Problem loading main window position : " + ex.Message);
			}

			try
			{
				if (settings.MainWindow.SplitterDistance > 0)
					this.splitContainer.SplitterDistance = settings.MainWindow.SplitterDistance;
			}
			catch (Exception ex)
			{
				Log.Error("Problem loading main window splitter position : " + ex.Message);
			}

			try
			{
				if (settings.MainWindow.CurrentView >= 0)
				{
					this.multiPageTabControl.SelectedIndex = settings.MainWindow.CurrentView;
					//this.SubView = (SubView)settings.MainWindow.CurrentView;

					//this.SubViewChanged.Fire(this, new SubViewEventArgs(this.SubView));
				}
			}
			catch (Exception ex)
			{
				Log.Error("Problem loading main window sub page index : " + ex.Message);
			}

			try
			{
				this.WindowState = (settings.StartMinimized) ? FormWindowState.Minimized : FormWindowState.Normal;
			}
			catch (Exception ex)
			{
				Log.Error("Problem loading main window start minimized : " + ex.Message);
			}

		}

		#endregion

		#region Main Window Event Handlers

		private void MainForm_Load(object sender, EventArgs e)
		{
			Log.Debug(Resources.Log_LoadingMainForm);

			this.Initialising.Fire(this);

			this.pollingTimer.Enabled = false;
			this.startupTimer.Enabled = false;

			InversionOfController.Factory.CreateTypeOf<ITaskbarManager>().RegisterApplication(MainFormAppID);

			this.ConfigureUI();

			this.DriveDetector.RemovableDriveArrived += new EventHandler<RemovableDriveEventArgs>(DriveDetector_RemovableDriveArrived);
			this.DriveDetector.RemovableDriveRemoved += new EventHandler<RemovableDriveEventArgs>(DriveDetector_RemovableDriveRemoved);

			this.InitialiseComplete.Fire(this);
		}

		private void MainForm_Resize(object sender, System.EventArgs e)
		{
			//if (this.WindowState == FormWindowState.Minimized)
			//{
			//    this.Hide();
			//}
		}

		private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
            if (this.Refreshing || this.Downloading || this.Transferring)
            {
                MessageBox.Show("Cannot shut down yet");
                e.Cancel = true;
                return;
            }

			Log.Debug("Closing Main form");

			this.startupTimer.Enabled = false;
			this.pollingTimer.Enabled = false;

			notifyIcon1.Dispose();

			// check nothing else needs shutting down....
			this.ClosingView.Fire(this);
		}

		private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			RestoreView();
		}

		private void notifyContextMenuItemOpen_Click(object Sender,EventArgs e) 
		{
			RestoreView(); 
		}

		private void RestoreView()
		{
			if (this.WindowState == FormWindowState.Minimized)
				this.WindowState = FormWindowState.Normal;

			this.ShowInTaskbar = true;
			this.Show();
			this.BringToFront();
		} 
 
		private void notifyContextMenuItemExit_Click(object Sender,EventArgs e) 
		{ 
			this.notifyIcon1.Dispose(); 
			Application.Exit(); 
		}
 
		void MainForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if (e.KeyCode == Keys.F5)
			{
				// do refresh...
				StartRefreshEpisodes();
			}
			else if (e.KeyCode == Keys.F10)
			{
				int count = this.multiPageTabControl.TabCount;

				if (this.multiPageTabControl.SelectedIndex < (count - 1))
					this.multiPageTabControl.SelectedIndex++;
				else
					this.multiPageTabControl.SelectedIndex = 0;
			}
		}

		#region Drag and Drop Support

		private void ConfigureAsFileDropTarget()
		{
			this.AllowDrop = true;
			this.DragEnter += new DragEventHandler(MainForm_DragEnter);
			this.DragOver += new DragEventHandler(MainForm_DragOver);
			this.DragDrop += new DragEventHandler(MainForm_DragDrop);
		}

		void MainForm_DragDrop(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				string[] draggedFiles = (string[])e.Data.GetData(DataFormats.FileDrop);

				var copyList = new List<string>();

				foreach (string file in draggedFiles)
				{
					if (file.EndsWith(OpmlDocument.FileExtension, StringComparison.CurrentCultureIgnoreCase))
					{
						Log.Info("Attempting to import from dragged file " + file);

						this.ImportPodcasts.Fire(this, new FilePersistenceEventArgs(file));
					}
					else if (file.EndsWith(FileConstants.Mp3FileExtension, StringComparison.CurrentCultureIgnoreCase))
					{
						copyList.Add(file);
					}
					else if (file.EndsWith(PlaylistConstants.Mp3PlaylistExtension) || file.EndsWith(PlaylistConstants.WindowsPlaylistExtension))
					{
						this.CopyPlaylist.Fire(this, new FilePersistenceEventArgs(file));
					}
					else
					{
						Log.Info("Not valid format");
					}
					// add url
				}

				if (copyList.Count > 0)
				{
					this.CopyFiles.Fire(this, new MultiFilePersistenceEventArgs(copyList));
				}

			}
			else if (e.Data.GetDataPresent(DataFormats.UnicodeText))
			{
				string draggedText = (string)e.Data.GetData(DataFormats.UnicodeText);

				Log.Info("Attempting to add new dragged url " + draggedText);

				// add url
				try
				{
					// attempt a url to see if it is the right format...
					Uri candidateFeed = new Uri(draggedText);

					//this.subscriptionView1.AddFeed(draggedText, string.Empty);

				}
				catch (FormatException)
				{
					Log.Info("Url in wrong format");
				}
			}
		}

		void MainForm_DragOver(object sender, DragEventArgs e)
		{
		}

		void MainForm_DragEnter(object sender, DragEventArgs e)
		{
			// we can accept a file - opml to import perhaps...
			// or if it's a url - try to add it...

			if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent(DataFormats.UnicodeText))
				e.Effect = DragDropEffects.Copy;
		}

		#endregion

		#endregion Main Window Events
		
		#region Control Events

		void sortableListView_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.A && e.Control)
			{
				var list = sender as SortableListView;

				if (list != null && list.MultiSelect)
				{
					foreach (ListViewItem item in list.Items)
					{
						item.Selected = true;
					}
				}
			}
		}

		private void mediaPlayerStatusLabel_Click(object sender, EventArgs e)
		{
			using (SelectMediaDeviceForm selectDevice = new SelectMediaDeviceForm())
			{
				if (DialogResult.OK == selectDevice.ShowDialog())
				{

				}
			}
		}

		private void refreshButton_Click(object sender, EventArgs e)
		{
			StartRefreshEpisodes();
		}

		private void StartRefreshEpisodes()
		{
			this.startupTimer.Enabled = this.pollingTimer.Enabled = false;

			this.CheckForEpisodes.Fire(this);
		}

		private void downloadButton_Click(object sender, EventArgs e)
		{
			EpisodeListView elv = this.newEpisodesListView;

			if (this.multiPageTabControl.SelectedIndex == (int)TabbedPageView.NewEpisodes)
			{
				elv = this.newEpisodesListView;
			}
			else if (this.multiPageTabControl.SelectedIndex == (int)TabbedPageView.BackCatalog)
			{
				elv = this.podcastSpecificEpisodesListView;
			}

			if (elv != null)
			{
				var downloadDbKeys = new List<int>();

				foreach (var item in elv.CheckedItems)
				{
					var episodeItem = item as EpisodeListViewItem;

					if (episodeItem != null)
					{
						downloadDbKeys.Add(episodeItem.DbKey);
					}
				}

				this.DownloadEpisodes.Fire(this, new EpisodeDownloadEventArgs(downloadDbKeys));
			}
		}


		void multiPageTabControl_Selecting(object sender, System.Windows.Forms.TabControlCancelEventArgs e)
		{
			if (this.multiPageTabControl.SelectedIndex == (int)TabbedPageView.MediaPlayer)
			{
				if (this.synchPlayerButton.Enabled)
				{
					// refresh the display...
					this.RefreshPortableDevice.Fire(this);
				}
				else
				{
					e.Cancel = true;
				}
			}
		}
		
		private void showToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Show();
			this.WindowState = FormWindowState.Normal;
		}

		private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
		{

		}

		void startupTimer_Tick(object sender, System.EventArgs e)
		{
			StartRefreshEpisodes();
		}

		private void pollingTimer_Tick(object sender, EventArgs e)
		{
			StartRefreshEpisodes();
		}

		private void settingsButton_Click(object sender, EventArgs e)
		{
			using (var settings = new SettingsManagement(this.Presenter.Model.Settings))
			{
				var settingsPresenter = new ApplicationSettingsPresenter(settings, this.Presenter.Model.Settings);

				settings.ShowDialog();

                settings.Settings.Save();

                this.Presenter.Model.ReloadSettings();
			}
		}

		private void manageSubscriptionsButton_Click(object sender, EventArgs e)
		{
			using (var dialog = new SubscriptionManagement())
			{
				var subscriptionPresenter = new SubscriptionPresenter(dialog, this.Presenter.Model);

				dialog.ShowDialog();

				// now refresh the window...
				this.RefreshNavigationList.Fire(this);
			}
		}

		private void addSubscriptionButton_Click(object sender, EventArgs e)
		{
			var addSubscription = AddPodcast;

			if (addSubscription != null)
			{
				using (AddPodcastForm addDialog = new AddPodcastForm())
				{
					if (DialogResult.OK == addDialog.ShowDialog())
					{
						addSubscription(this, new NewPodcastEventArgs(addDialog.SelectedFeed, addDialog.SelectedName));
					}
				}

			}
		}

		void synchPlayerButton_Click(object sender, System.EventArgs e)
		{
			this.TransferContent.Fire(this, new TransferCommandEventArgs(true));
		}

		private void searchButton_Click(object sender, EventArgs e)
		{
			//if (this.multiPageTabControl.SelectedIndex == HomePageIndex)
			//{
			//    var searchEpisodes = SearchEpisodes;

			//    if (searchEpisodes != null && !string.IsNullOrEmpty(searchTextBox.Text))
			//        searchEpisodes(this, new SearchEventArgs(searchTextBox.Text));
			//}
			//else if (this.multiPageTabControl.SelectedIndex == WelcomePageIndex)
			//{
			//    var node = this.treeView.SelectedNode;

			//    if (node != null && node.Text != "Podcasts")
			//    {
			//        var searchPodcast = SearchPodcast;

			//        if (searchPodcast != null && !string.IsNullOrEmpty(searchTextBox.Text))
			//        {
			//            string id = node.Tag as string;

			//            if (!string.IsNullOrEmpty(id))
			//            {
			//                searchPodcast(this, new PodcastSearchEventArgs(id, searchTextBox.Text));
			//            }
			//        }
			//    }
			//    else
			//    {
			//        var searchPodcasts = SearchPodcasts;

			//        if (searchPodcasts != null && !string.IsNullOrEmpty(searchTextBox.Text))
			//        {
			//            searchPodcasts(this, new SearchEventArgs(searchTextBox.Text));
			//        }
			//    }
			//}

		}

		#endregion Control Events

		#region IPodcatcherView Methods

		public void LogErrors(List<string> errors)
		{
			foreach (string errorMessage in errors)
				Log.Error(errorMessage);

			if (errors.Count == 1)
				MessageBox.Show(errors[0], Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
		}

		public void ShowPodcastInfo(Podcast podcast, EpisodeCollection episodes)
		{
			//if (this.SubView == Core.SubView.BackCatalog)
			//{
				//t//his.multiPageTabControl.SelectedIndex = HomePageIndex;
				this.podcastSpecificEpisodesListView.RefreshContent(episodes);
			//}
		}

		public void ShowDeviceStatus(PortableMediaViewModel vm)
		{
			this.synchPlayerButton.Enabled = vm.Connected;
		}

		public void RefreshDeviceStatus(PortableMediaViewModel vm)
		{
			if (vm.Connected)
			{
				this.navigationListView.RefreshMediaPlayer(vm.VolumeLabel, vm.Connected);
				this.portableDeviceView1.RefreshDeviceStatus(vm);

				this.portableDeviceContentView1.RefreshContent(vm.DriveName);
				ShowTooltip(string.Format ("{0} connected", vm.VolumeLabel));
			}
			else
			{
				int selectedIndex = this.multiPageTabControl.SelectedIndex;

				if (selectedIndex == (int)TabbedPageView.MediaPlayer || selectedIndex == (int)TabbedPageView.MediaPlayerContent)
				{
					this.multiPageTabControl.SelectedIndex = (int)TabbedPageView.Subscriptions;
					this.SubscriptionsSelected.Fire(this);
				}

				this.navigationListView.RefreshMediaPlayer(vm.VolumeLabel, vm.Connected);
				this.portableDeviceView1.RefreshDeviceStatus(vm);
				this.portableDeviceContentView1.ClearContent();
				ShowTooltip(string.Format("{0} removed", vm.VolumeLabel));
			}

			this.synchPlayerButton.Enabled = vm.Connected;
		}

        public void SettingsLoaded(IUserSettings settings)
		{
			this.LoadLastSizeAndPosition(settings);

			//this.portableDeviceView1.CheckConnection(settings.MediaPlayer);

			// insert items into subscriptions view...
			this.podcastSubscriptionListView.Configure();
			this.podcastSubscriptionListView.MessageWhenEmpty = "No podcasts loaded.";

			this.podcastSpecificEpisodesListView.Configure(ListConfiguration.ShowCheckBoxes);
			this.podcastSpecificEpisodesListView.MessageWhenEmpty = "No episodes for podcast found yet.";

			this.downloadedEpisodesListView.Configure(ListConfiguration.HideCheckBoxes);
			this.downloadedEpisodesListView.MessageWhenEmpty = "Nothing waiting for transfer yet.";
			this.newEpisodesListView.Configure(ListConfiguration.ShowCheckBoxes);
			this.newEpisodesListView.MessageWhenEmpty = "No new episodes yet.";

			this.portableDeviceContentView1.InitialiseUI();

			this.ShowTooltips = settings.ShowTooltips;
			this.TooltipTimeout = settings.TooltipTimeout;

			this.startupTimer.Interval = settings.Polling.StartupDelayMilliseconds;
			this.pollingTimer.Interval = settings.Polling.PollingIntervalMilliseconds;
			this.startupTimer.Enabled = true;
		}

		public void LoadSearchResults(PodcastCollection collection)
		{
			this.podcastSubscriptionListView.RefreshContent(collection);
		}

		public void LoadSubscriptions(PodcastCollection collection)
		{
			//this.podcastSubscriptionListView.RefreshContent(collection);

			this.navigationListView.RefreshContent(collection);
		}

		public void ShowSubscriptionList(PodcastCollection collection)
		{
			//this.ma
			this.multiPageTabControl.SelectedIndex = (int)TabbedPageView.Subscriptions;

			this.currentSubscriptionsListView.RefreshContent(collection);
		}

		public void LoadNewEpisodes(EpisodeCollection collection)
		{
		    this.newEpisodesListView.RefreshContent(collection);
		}

		public void LoadDownloadedEpisodes(EpisodeCollection collection)
		{
		    this.downloadedEpisodesListView.RefreshContent(collection);
		}

		public void LoadPodcastEpisodes(EpisodeCollection collection)
		{
			if (this.multiPageTabControl.SelectedIndex != (int)TabbedPageView.BackCatalog)
			{
				this.multiPageTabControl.SelectedIndex = (int)TabbedPageView.BackCatalog;
			}

			this.podcastSpecificEpisodesListView.RefreshContent(collection);
		}

        public void SettingsChanged(IUserSettings settings)
		{
			//this.CheckConnection(settings.MediaPlayer);
		}

		#region IShowProgress

		public int MaxItems
		{
			get { return 0; } // this.progressView1.ProgressMaximum; }
			set
			{
				//if (!this.progressView1.Visible)
				//    this.progressView1.Visible = true;

				//this.progressPanel.Visible = true;
				//this.progressView1.ProgressMaximum = value;
			}
		}

		public void Increment()
		{
			//if (!this.progressView1.Visible)
			//    this.progressView1.Visible = true;

			//this.progressPanel.Visible = true;

			//int newValue = this.progressView1.ProgressValue + 1;

			//if (newValue <= this.progressView1.ProgressMaximum)
			//    this.progressView1.ProgressValue = newValue;
		}

		public void Reset()
		{
			//this.progressView1.ProgressValue = 0;
			//this.progressView1.Visible = false;
			//this.progressPanel.Visible = false;
		}

		#endregion IShowProgress

		public void RssRefreshStarting(int items)
		{
			this.refreshButton.Enabled = false;
            this.Refreshing = true;
			this.RefreshingItemCount = items;
			ShowTooltip(string.Format("Refreshing {0} feeds", items));
			InversionOfController.Factory.CreateTypeOf<IProgressIndicator>().StartProgressIndicator(items);
		}

		public void RssRefreshProgress(int item)
		{
			this.refreshButton.Enabled = false;
			InversionOfController.Factory.CreateTypeOf<IProgressIndicator>().UpdateProgressIndicator(item, this.RefreshingItemCount);
		}

		public void RssRefreshFinished(int newItems)
		{
			this.refreshButton.Enabled = true;
			this.pollingTimer.Enabled = true;
            this.Refreshing = false;
			this.RefreshingItemCount = 0;

			string statusMessage;

			if (newItems == 0)
			{
				statusMessage = "Could not find any new episodes";
			}
			else
			{
				statusMessage = string.Format("Found {0} new episodes", newItems);
			}

			ShowTooltip(statusMessage);

			InversionOfController.Factory.CreateTypeOf<IProgressIndicator>().StopProgressIndicator();
		}

		public void TransferStarting(int items)
		{
			this.synchPlayerButton.Enabled = false;
            this.Transferring = true;
			this.TransferringItemCount = items;
			ShowTooltip(string.Format("Synching {0} files", items));
			InversionOfController.Factory.CreateTypeOf<IProgressIndicator>().StartProgressIndicator(items);
		}

		public void TransferProgress(int item)
		{
			this.synchPlayerButton.Enabled = false;
			InversionOfController.Factory.CreateTypeOf<IProgressIndicator>().UpdateProgressIndicator(item, this.TransferringItemCount);
		}

		public void TransferFinished(int items)
		{
			this.synchPlayerButton.Enabled = true;
            this.Transferring = false;
			this.TransferringItemCount = 0;
            ShowTooltip(string.Format("Synched {0} files", items));
			InversionOfController.Factory.CreateTypeOf<IProgressIndicator>().StopProgressIndicator();
		}


		public void EnableTransfer(bool enable)
		{
			this.synchPlayerButton.Enabled = enable;
		}

		public void ShowEpisodes(EpisodeCollection episodes)
		{
		}

		public void RefreshEpisodes(EpisodeCollection episodes)
		{
		}

		public void ShowEpisodeInfo(Episode episode)
		{
		}

		public void EpisodeDownloadStarting(int items)
		{
			this.downloadButton.Enabled = false;
            this.Downloading = true;
			this.DownloadingItemCount = items;
			ShowTooltip(string.Format("Downloading {0} files", items));
			InversionOfController.Factory.CreateTypeOf<IProgressIndicator>().StartProgressIndicator(items);
		}

		public void EpisodeDownloadProgress(int item)
		{
			InversionOfController.Factory.CreateTypeOf<IProgressIndicator>().UpdateProgressIndicator(item, this.DownloadingItemCount);
		}

		public void EpisodeDownloadFinished(int items)
		{
			this.downloadButton.Enabled = true;
            this.Downloading = false;
			this.DownloadingItemCount = 0;
			ShowTooltip(string.Format("Downloaded {0} files", items));
			InversionOfController.Factory.CreateTypeOf<IProgressIndicator>().StopProgressIndicator();
		}

		public void ReportError(string message)
		{
			MessageBox.Show(message, Application.ProductName,
								MessageBoxButtons.OK, MessageBoxIcon.Information,
								MessageBoxDefaultButton.Button1);
		}

		private void ShowTooltip(string message)
		{
			if (this.ShowTooltips)
			{
				this.notifyIcon1.ShowBalloonTip(this.TooltipTimeout,
												this.Text,
												message,
												ToolTipIcon.Info);
			}
		}

		#endregion IPodcatcherView Methods

        private void ignoreEpisodeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (newEpisodesListView.SelectedItems.Count > 0)
            {
				List<int> ids = new List<int>();

                foreach (var item in newEpisodesListView.SelectedItems)
				{
					var episodeItem = item as EpisodeListViewItem;

					if (episodeItem != null)
					{
						ids.Add(episodeItem.DbKey);
					}
				}

				this.IgnoreEpisode.Fire(this, new EpisodeEventArgs(ids, true));
            }
        }

	}
}
